package com.examples.text;

import java.io.FileWriter;
import java.io.IOException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class NotepadExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Display d = new Display();
		final Shell s = new Shell(d);

		s.setLayout(new FillLayout());
		s.setText("Untitled - Notepad");

		final Text t = new Text(s, SWT.MULTI);

		s.addListener(SWT.Dispose, new Listener() {

			@Override
			public void handleEvent(Event event) {
				if (t.getText() != "") {
					MessageBox mb = new MessageBox(s, SWT.OK | SWT.CANCEL);
					mb.setMessage("Do you want to save changes to Untitled?");
					mb.setText("Notepad");
					if (mb.open() == SWT.OK) {
						FileDialog fd = new FileDialog(s, SWT.SAVE);
						fd.setText("Save");
						fd.setFilterPath("C:/");
						String[] filterExt = { ".txt", "*.doc", ".rtf", "*.*" };
						fd.setFilterExtensions(filterExt);
						String selected = fd.open();
						try {
							if (selected != null) {
								@SuppressWarnings("resource")
								FileWriter fileWriter = new FileWriter(selected);
								fileWriter.write(t.getText());
								fileWriter.flush();
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

				}
			}
		});

		s.open();
		while (!s.isDisposed()) {
			if (!d.readAndDispatch()) {
				d.sleep();
			}
		}
	}

}
